package com.idp.web.test.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.idp.common.base.BaseController;
import com.idp.common.persistence.Page;
import com.idp.common.util.ExcelUtil;
import com.idp.common.util.FileUtils;
import com.idp.common.util.ValidateUtils;
import com.idp.web.test.entity.Product;
import com.idp.web.test.entity.ProductType;
import com.idp.web.test.entity.Put;
import com.idp.web.test.entity.PutStatus;
import com.idp.web.test.entity.Warehouse;
import com.idp.web.test.service.ProductService;
import com.idp.web.test.service.ProductTypeService;
import com.idp.web.test.service.PutService;
import com.idp.web.test.service.PutStatusService;
import com.idp.web.test.service.StockService;
import com.idp.web.test.service.WarehouseService;

import net.sf.json.JSONObject;

/**
 * 
 * 11111controller
 * 
 * <pre>
 * 	历史记录：
 * 	2017-06-02 Amber
 * 	新建文件
 * </pre>
 * 
 * @author
 * 
 * 		<pre>
 * SD
 * 	Amber
 * PG
 *	Amber
 * UT
 *
 * MA
 *         </pre>
 * 
 * @version $Rev$
 *
 *          <p/>
 *          $Id$
 *
 */
@Controller
@RequestMapping("/put")
public class PutController extends BaseController {

	private Logger logger = Logger.getLogger(PutController.class);

	@Resource
	private PutService putService;

	@Resource
	private ProductTypeService productTypeService;

	@Resource
	private WarehouseService warehouseService;

	@Resource
	private PutStatusService putStatusService;

	@Resource
	private StockService stockService;

	@Resource
	private ProductService productService;

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	初始化查询页面
	 * </pre>
	 * 
	 * @return
	 */
	@RequestMapping("/init")
	public String init(HttpServletRequest request) {

		try {
			request.setAttribute("warehouses", warehouseService.findBySearch(new Warehouse()));
			request.setAttribute("putStatus", putStatusService.findBySearch(new PutStatus()));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shopping/put/putSearch";
	}

	@RequestMapping("/searchList")
	public String searchList(Put put, Page<Put> page, HttpServletRequest request) {
		try {
			if (put.getWarehouseId() == 0) {
				put.setWarehouseId(null);
			}
			if (put.getPutStatusId() == 0) {
				put.setPutStatusId(null);
			}
			request.setAttribute("page", putService.findByPage(put, page));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shopping/put/putList";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	新增修改页面初始化
	 * </pre>
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/put")
	public String put(Integer id, HttpServletRequest request) {
		try {
			ProductType productType = new ProductType();
			productType.setParent(0);
			//System.out.println(id);
			List<Warehouse> warehouses = warehouseService.findBySearch(new Warehouse());
			List<Product> products = productService.findBySearch(new Product());
			List<ProductType> productTypes = productTypeService.findBySearch(productType);
			if (ValidateUtils.isNotEmpty(id)) {
				Put put = putService.getById(id);
				request.setAttribute("put", put);
				for (Warehouse w : warehouses) {
					if (w.getId() == put.getWarehouseId()) {
						warehouses.remove(w);
						break;
					}
				}
				for (Product p : products) {
					if (p.getId() == put.getProductId()) {
						products.remove(p);
						break;
					}
				}
				for (ProductType pt : productTypes) {
					if (pt.getId() == put.getProduct().getProductTypeId()) {
						productTypes.remove(pt);
						break;
					}
				}
			}
			request.setAttribute("warehouses", warehouses);

			request.setAttribute("products", products);

			request.setAttribute("productTypes", productTypes);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shopping/put/put";
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	保存
	 * </pre>
	 * 
	 * @param put
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(Put put, HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			if (ValidateUtils.isNotEmpty(put.getId())) {
				put.setPutStatusId(null);
				putService.updateNotNull(put);
			} else {
				putService.add(put);
			}
			json.put("result", "save_success");
		} catch (Exception e) {

			logger.error(e.getMessage(), e);
			json.put("result", "save_fail");
		}

		return json.toString();
	}

	/**
	 * 
	 * <pre>
	 * 	2017-06-02 Amber
	 * 	删除
	 * </pre>
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(Integer id) {
		JSONObject json = new JSONObject();
		Put put = new Put();
		try {
			put.setId(id);
			put.setPutStatusId(6);
			putService.updateNotNull(put);
			json.put("result", "delete_success");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.put("result", "delete_fail");
		}
		return json.toString();
	}

	/**
	 * 批量导出
	 * 
	 * @param warehouseId
	 * @param statusId
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/batchExport")
	public String batchExport(Integer warehouseId, Integer statusId, String beginTime, String endTime,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<>();
		map.put("warehouseId", warehouseId);
		Warehouse warehouse = warehouseService.getById(warehouseId);
		PutStatus putStatus = new PutStatus();
		if (statusId != 0) {
			map.put("statusId", statusId);
			putStatus = putStatusService.getById(statusId);
		} else {
			putStatus.setName("全部");
		}
		if (!"".equals(beginTime)) {
			map.put("beginTime", beginTime);
		}
		if (!"".equals(endTime)) {
			map.put("endTime", endTime);
		}
		List<Put> puts = putService.findByMap(map);
		HSSFWorkbook workbook = ExcelUtil.createPutWorkBook(puts);
		// --------------------------- //
		String fileName = warehouse.getName() + "-" + putStatus.getName() + "-" + beginTime + "至" + endTime;
		fileName = FileUtils.encodingFileName(fileName);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			workbook.write(os);
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// 设置reponse参数,打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
			ServletOutputStream sos = response.getOutputStream();
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(sos);
			byte[] buff = new byte[2048];
			int bytesRead = 0;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				bis.close();
			}
			if (bos != null) {
				bos.close();
			}
		}
		return null;
	}

	/**
	 * 批量导入
	 * 
	 * @param multipartFile
	 * @return
	 */
	@RequestMapping("/batchPut")
	@ResponseBody
	public String batchPut(@RequestParam(value = "recordfile", required = true) MultipartFile multipartFile,
			Integer warehouse) {
		JSONObject json = new JSONObject();
		json.put("msg", "导入失败,请确保导入文件的格式正确");
		// 创建对Excel工作簿文件的引用
		HSSFWorkbook workbook;
		try {
			// 获取控件内容的输入流
			InputStream is = multipartFile.getInputStream();
			workbook = new HSSFWorkbook(is);
			// 获取sheet表的总数量
			int numberOfSheet = workbook.getNumberOfSheets();
			for (int k = 0; k < numberOfSheet; k++) {
				// 创建对工作表的引用。
				HSSFSheet sheet = workbook.getSheetAt(k);
				System.out.println("当前sheet表为：" + workbook.getSheetName(k));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String value = "";
				if ("入库表".equals(workbook.getSheetName(k))) {
					// 读取所有单元格
					for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
						Put put = new Put();
						Product product = new Product();
						for (int j = 0; j < sheet.getRow(i).getPhysicalNumberOfCells(); j++) {
							HSSFCell cell = sheet.getRow(i).getCell(j);
							if (cell == null)
								break;
							// 单元格意义
							String rc0 = sheet.getRow(0).getCell(j).getStringCellValue();
							switch (cell.getCellType()) {
							case HSSFCell.CELL_TYPE_NUMERIC: // 数字
								// 如果为时间格式的内容
								if (HSSFDateUtil.isCellDateFormatted(cell)) {
									value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
									break;
								} else {
									DecimalFormat dcmFmt = new DecimalFormat("0");
									value = String.valueOf(dcmFmt.format(cell.getNumericCellValue()));
								}
								break;
							case HSSFCell.CELL_TYPE_STRING: // 字符串
								value = cell.getStringCellValue();
								break;
							case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
								value = cell.getBooleanCellValue() + "";
								break;
							case HSSFCell.CELL_TYPE_FORMULA: // 公式
								// value = cell.getCellFormula() + "";
								try {
									DecimalFormat dcmFmt = new DecimalFormat("0");
									value = String.valueOf(dcmFmt.format(cell.getNumericCellValue())) + "";
								} catch (IllegalStateException e) {
									cell.setCellType(HSSFCell.CELL_TYPE_STRING);
									value = String.valueOf(cell.getRichStringCellValue()) + "";
								}
								break;
							case HSSFCell.CELL_TYPE_BLANK: // 空值
								value = "";
								break;
							case HSSFCell.CELL_TYPE_ERROR: // 故障
								value = "非法字符";
								break;
							default:
								value = "未知类型";
								break;
							}
							if ("SKU".equals(rc0)) {
								product = productService.getByCode(value);
							}
							if ("箱数".equals(rc0)) {
								System.err.println(value);
								try {
									put.setBox(Integer.parseInt(value));
								} catch (NumberFormatException e) {
									System.err.println("error:表格中箱数为非数字");
								}
							}
							if ("出货数量".equals(rc0)) {
								System.err.println(value);
								try {
									put.setRealbox(Integer.parseInt(value));
								} catch (NumberFormatException e) {
									System.err.println("error:表格中出货数量为非数字");
								}
							}
						}
						try {
							put.setWarehouseId(warehouse);
							put.setProductId(product.getId());
							putService.add(put);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					json.put("msg", "导入成功");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json.toString();
	}

	/**
	 * 批量确认入库信息
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/batchMakeSure")
	@ResponseBody
	public String batchMakeSure(@RequestParam(value = "ids[]", required = false) Integer[] ids) {
		JSONObject jsonObject = new JSONObject();
		int result = putService.makeSurePut(ids);
		if (result == 1) {
			jsonObject.put("result", "success");
		} else {
			jsonObject.put("result", "faile");
		}
		return jsonObject.toString();
	}
}